extends CharacterBody2D
var can_slide=true
const SPEED = 300.0
const JUMP_FORCE = 700.0
const PUSH_FORCE = 1000.0
const SLIDE_FORCE = 2000.0 
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var is_sliding = false
var anime:AnimationPlayer
func _ready():
	anime=$AnimationPlayer
	velocity.y = -JUMP_FORCE * 2
	
func _physics_process(delta):
	apply_gravity(delta)
	handle_jump()
	handle_horizontal_movement()
	constrain_position()
	move_and_slide()

func _process(delta):
	if is_sliding:
		anime.play('parachute')
	elif velocity.x==0:
			anime.play('Idle')
	elif velocity.x<0:
		if is_on_floor():
			anime.play('walk_right')
		elif velocity.y>50:
			anime.play('fall_right')
	elif velocity.x>0:
		if is_on_floor():
			anime.play('walk_left')
		elif velocity.y>50:
			anime.play('fall_left')
func apply_gravity(delta):
	if not is_on_floor() and not is_sliding:  # No gravity while sliding
		velocity.y += gravity * delta

func handle_jump():
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = -JUMP_FORCE

func handle_horizontal_movement():
	var direction = Input.get_axis("move_left", "move_right")
	if direction != 0:
		velocity.x = direction * SPEED
	elif not is_sliding:  # Only decelerate if not sliding
		velocity.x = move_toward(velocity.x, 0, SPEED * 0.1)  # Deceleration with friction

func _input(event):
	# Start sliding when "Shift" is pressed and the player is in the air
	if event.is_action_pressed("slide") and not is_on_floor() and not is_sliding and can_slide:
		start_slide()

func start_slide():
	is_sliding = true
	velocity.x = sign(velocity.x) * SLIDE_FORCE  # Slide in the current horizontal direction
	velocity.y =0
	$SlideTimer.start()  # Start the slide timer

func constrain_position():
	if global_position.y > -549:
		global_position = Vector2(0, -550)

func _on_area_2d_area_entered(area):
	if area.is_in_group("bubble"):
		handle_bubble_collision(area)
	elif area.is_in_group('bee'):
		velocity.y = -JUMP_FORCE
	elif area.is_in_group('bullet'):
		global_position=-Vector2(0,550)



func handle_bubble_collision(area):
	if area.global_position.y > global_position.y + 10:
		velocity.y = -JUMP_FORCE * randf_range(1, 3)
		can_slide=true
		anime.play('bubble_push')
	elif abs(area.global_position.x - global_position.x) > 10:
		velocity.x += PUSH_FORCE if area.global_position.x < global_position.x else -PUSH_FORCE
		

func _on_slide_timer_timeout():
	is_sliding=false
	can_slide=false
		
